#ifndef _MP4V2_RECORD_H_
#define _MP4V2_RECORD_H_

#include "mp4v2/mp4v2.h"
#include <pthread.h>
#include <stdbool.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>

typedef struct {
    int segment_duration_sec; // 分段时长 (秒)
    char storage_path[256];   // 存储路径 (目录)
    int queue_size;           // NALU 队列大小
    int video_width;          // 视频宽度
    int video_height;         // 视频高度
    int video_fps;            // 视频帧率 (用于计算 duration)
    // Add other parameters as needed (e.g., audio config)
} RecConfig;

// --- NALU Queue (Thread-Safe) ---

typedef struct {
    uint8_t* data;       // 指向 NALU 数据 (已复制)
    size_t   size;       // NALU 数据大小
    uint64_t pts;        // 源时间戳 (例如，90kHz 时钟) - 用于调试或精确同步
    int     is_keyframe;// 是否是关键帧 (I-Frame)
    uint8_t  nalu_type;  // NALU 类型 (7 for SPS, 8 for PPS, 5 for IDR, 1 for non-IDR slice)
} NaluPacket;

typedef struct {
    NaluPacket* buffer;      // Pointer to allocated buffer array
    int capacity;
    int head;
    int tail;
    int count;
    pthread_mutex_t mutex;
    pthread_cond_t not_empty;
    pthread_cond_t not_full;
    int shutdown;           // 0 = running, 1 = shutting down
} NaluQueue;

// --- MP4 Recorder Module ---
// 录像线程状态
typedef struct {
    NaluQueue* queue;            // 指向共享队列
    RecConfig config;            // 录像配置
    MP4FileHandle mp4File;       // 当前 MP4 文件句柄
    MP4TrackId videoTrack;     // 视频轨道 ID
    char current_filename[512];  // 当前临时文件名
    time_t segment_start_time;   // 当前分段开始时间
    uint64_t next_pts;           // 期望的下一个 PTS (90kHz) - 用于计算 duration
    int first_frame_written;    // 是否已写入第一帧（关键帧）
    uint8_t* sps_data;           // 保存的 SPS NALU (AVCC 格式)
    uint32_t sps_size;
    uint8_t* pps_data;           // 保存的 PPS NALU (AVCC 格式)
    uint32_t pps_size;
    int sps_pps_received;       // 是否已收到 SPS/PPS
    pthread_t thread_id;
    volatile int running;       // 控制线程运行
    int is_recording_enabled;
} RecorderState;

int nalu_queue_init(NaluQueue* q, int capacity);
int nalu_queue_push(NaluQueue* q, const uint8_t* data, size_t size, uint64_t pts, int is_keyframe, uint8_t nalu_type);
int nalu_queue_pop(NaluQueue* q, NaluPacket* packet);
void nalu_queue_destroy(NaluQueue* q);
void nalu_queue_shutdown(NaluQueue* q);
int process_and_push_frame(const uint8_t* frame_data, size_t frame_size, uint64_t frame_pts);
void simulate_h264_source();
void handle_signal(int sig);
int get_recording_enabled();
void* recorder_thread_func(void* arg);

/**
 * @brief 停止录像线程并保存当前录像文件，应在设备重启前调用
 * 
 * @return 0 成功，-1 失败
 */
int stop_recorder_and_save(void);

/**
 * @brief Enables or disables MP4 recording. Thread-safe.
 *
 * @param enable True to enable recording, false to disable.
 */
void set_recording_enabled(int enable);

#endif //_MP4V2_MP4_H_